#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <string.h>
#include <stdlib.h>
#include <error.h>

#include "myapp.h"

#define BUFFERSIZE 1024

int http_get (const char *url, const char *cookies, char *reply)
{
    char hostname[100];
    int port;
    char getstr[256];
    char buffer[BUFFERSIZE];
	int	sd;
	struct sockaddr_in pin;
	struct hostent *hp;
	int p;
	int rc, totalrc;
	char *t;

    // cek. url harus http:// atau https://
    if (strlen (url)<=10)
    {
        perror ("url terlalu pendek");
        return 0;
    }

    if (strncmp (url, "http://",7)==0 )
        port = 80;
    //else if (strncmp (url, "https://",8)==0 ) // eshabe: tidak jalan
    //   port = 443;
    else
    {
        perror ("url harus dimulai dg http://");
        perror (url);
        return 0;
    }

    p = strcspn (&url[7], "/");

#ifdef _DEBUG
    printf ("%s\np=%d\n", &url[7],p);
#endif

    strncpy (hostname, &url[7], p);
    hostname[p] = 0;

    t = strchr (hostname, ':');
    if (t!=NULL)
    {
        port = atoi (t+1);
        *t = 0; // ganti ':' dg 0
    }

#ifdef _DEBUG
    printf ("%s:%d\n", hostname, port);
#endif

	if ((hp = gethostbyname(hostname)) == 0)
	{
		perror("gethostbyname");
        return 0;
	}

	/* fill in the socket structure with host information */
	memset(&pin, 0, sizeof(pin));
	pin.sin_family = AF_INET;
	pin.sin_addr.s_addr = ((struct in_addr *)(hp->h_addr))->s_addr;
	pin.sin_port = htons(port);

	/* grab an Internet domain socket */
	if ((sd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
		perror("socket");
		exit(1);
	}

	/* connect to PORT on HOST */
	if (connect(sd,(struct sockaddr *)  &pin, sizeof(pin)) == -1) {
		perror("connect");
		exit(1);
	}

	/* send a message to the server PORT on machine HOST */
	sprintf (getstr, "GET %s HTTP/1.1\r\n" \
                      "Host: %s\r\n" \
                      "Cookie: %s\r\n" \
                      "Connection: close\r\n" \
                      "User-Agent: %s\r\n\r\n",
                      &url[p+7], hostname, cookies, APPNAME);

	//sprintf (getstr, "GET %s HTTP/1.1\r\n\r\n", &url[p+7]);
#ifdef _DEBUG
	printf ("%s\nlen=%d\n", getstr, strlen(getstr));
#endif
	if (send(sd, getstr, strlen(getstr), 0) == -1) {
		perror("send");
        return 0;
	}

    /* wait for a message to come back from the server */
    memset (reply, 0, MAXREPLY);
    memset (buffer, 0, BUFFERSIZE);
    totalrc = 0;
    while ((rc = recv(sd, buffer, BUFFERSIZE-1, 0)) >0 )
    {
        if (totalrc+rc>=MAXREPLY)
            break;

#ifdef _DEBUG
        printf ("%s\n", buffer);
#endif
        totalrc += rc;
        strcat (reply, buffer);
        memset (buffer, 0, BUFFERSIZE);
    }
    if (rc==-1)
    {
        perror("recv");
        return 0;
    }

	shutdown(sd, 2);
#ifdef _DEBUG
	printf ("totaldc=%d\n", totalrc);
#endif
    return 1;
}

float strtofloat (const char *str)
{
    char tmp[16];
    char *t;
    int l;

    strcpy (tmp, str);

#ifdef _DEBUG
	printf ("1. tmp = %s\n", tmp);
#endif

    while ( (t=strchr(tmp, '.'))!=NULL )
    {
        l = strlen(tmp);
        memmove (t, t+1, strlen(t));
        tmp[l] = 0;
    }

    if ( (t=strchr(tmp, ','))!=NULL )
        *t = '.';

#ifdef _DEBUG
	printf ("2. tmp = %s\n", tmp);
#endif

    return atof(tmp);
}

float strtoseconds (const char *str)
{
    int s=0;
    int m=0;
    int h=0;
    int p=0;

    char *t;
    char tmp[64];
    char dummy[64];

    strcpy (tmp, str);
    if ( (t=strrchr(tmp,':'))!=NULL )
    {
        strcpy (dummy, t+1);
        s = atoi(dummy);
        *t = 0;
        ++p;
#ifdef _DEBUG
    printf ("> %d - %s\n", s, dummy);
#endif
    }
    if ( (t=strrchr(tmp,':'))!=NULL )
    {
        strcpy (dummy, t+1);
        m = atoi(dummy);
        *t = 0;
        ++p;
#ifdef _DEBUG
    printf ("> %d - %s\n", m, dummy);
#endif
    }

    h = atoi(tmp);
    ++p;
#ifdef _DEBUG
    printf ("> %d - %s\n", h, dummy);
#endif

    if (p==1)
        return (float)(s*60*60);
    else if (p==2)
        return (float)(s*60+m*60*60);
    else if (p==3)
        return (float)(s+m*60+h*60*60);
    return 0;
}

void replacestr (char *src, const char *str, const char *rep)
{
    size_t l = strlen(src);
    char *tmp = malloc (l+1);
    char *dummy = malloc (l+1);
    char *t;

    if (tmp==NULL || dummy==NULL)
        return;
    while ( (t=strstr(src, str))!=NULL)
    {
        *t=0;
        strcpy (dummy, t+strlen(str));
        strcat (src, rep);
        strcat (src, dummy);
    }
}

void strip_tags (char *src)
{
    size_t l = strlen(src);
    char *tmp = malloc (l+1);
    char *dummy = malloc (l+1);
    char *t1, *t2;

    if (tmp==NULL || dummy==NULL)
        return;
    while ( (t1=strchr(src, '<'))!=NULL)
    {
        if ( (t2=strchr(t1, '>'))==NULL )
            break;
        *t1='!';
        memmove (t1+1, t2+1, strlen(t2)+1);
    }
}

void remove_header (char *str)
{
    char *t;

    if ( (t=strstr(str, "\r\n\r\n"))!=NULL )
    {
        memmove (&str[0], t+4, strlen(t+4)+1);
    }
}

void remove_head (char *str)
{
    char *t1, *t2;

    if ( (t1=strstr(str, "<head>"))!=NULL )
    {
        if ( (t2=strstr(t1, "</head>"))!=NULL )
        {
            memmove (t1, t2+7, strlen(t2+7)+1);
        }
    }
}


int getdata(const char *url, usageinfo *ui, char *msg)
{
	char reply[MAXREPLY];
	int get = 0;
	int p;
	char *t;
	char *t2;
	char tmp[32]; // eshabe: 16 --> 32. 16 masalah jika quota jam (20090401-1)
	float quota = 0;
	float penggunaan;
	int inMB = 0;

	if ( (get = http_get(url, "", reply)) != 1 )
        return get;

    remove_header (reply); // remove HTTP header
    remove_head (reply); // remove HTML head tag
    replacestr (reply, "<tr>", "!");
    replacestr (reply, "</tr>", "!");
    strip_tags (reply);
    replacestr (reply, "\t", " ");
    replacestr (reply, "\n", " ");
    replacestr (reply, "\r", " ");
    replacestr (reply, "  ", " ");
    replacestr (reply, "! !", "!");
    replacestr (reply, "!!", "!");
#ifdef _DEBUG
    puts (reply);
#endif
/*
!Info Pemakaian Speedy!111634100048!September&nbsp;2009!Sisa Quota! 0,00% !Quota!:!50:00:00!Pemakaian!:!143:36:56!Usage!:!100,00%!Sisa!:!0,00%!Kelebihan!:!93:36:56!Paket!:! Paket Timebased!
*/

    if ( (t=strstr(reply, "!Info Pemakaian Speedy!"))==NULL )
    {
        replacestr (reply, "!An Error Was Encountered!", "");
        strncpy (msg, reply, MAXMESSAGE-1);
        return -1; // tidak menemukan jawaban yg betul. mungkin salah url :)
    }

#ifdef _DEBUG
	printf ("* pengenal pertama ditemukan!\n");
#endif

    if ( (t2=strstr(reply, "!Quota!"))!=NULL )
    {
        if ((t=strstr(t2+2, "!:!"))==NULL)
            return -1;
        t += 3;
        p = strcspn (t, "!");
        strncpy (ui->quota, t, p);
        ui->quota[p] = 0;
#ifdef _DEBUG
        printf ("quota = %s\n", ui->quota);
#endif
    }

    if ( (t2=strstr(reply, "!Pemakaian!"))!=NULL )
    {
        if ((t=strstr(t2+2, "!:!"))==NULL)
            return -1;
        t += 3;
        p = strcspn (t, "!");
        strncpy (ui->penggunaan, t, p);
        ui->penggunaan[p] = 0;
#ifdef _DEBUG
        printf ("penggunaan = %s\n", ui->penggunaan);
#endif
    }

    if ( (t2=strstr(reply, "!Kelebihan!"))!=NULL )
    {
        if ((t=strstr(t2+2, "!:!"))==NULL)
            return -1;
        t += 3;
        p = strcspn (t, "!");
        strncpy (ui->kelebihan, t, p);
        ui->kelebihan[p] = 0;
#ifdef _DEBUG
        printf ("kelebihan = %s\n", ui->kelebihan);
#endif
    }
     // ambil "sisa" yg di atas kerena unlimited yg di bawah tidak ada. :(
    if ( (t2=strstr(reply, "!Sisa Quota!"))!=NULL )
    {
        if ((t=strstr(t2+2, "!"))==NULL)
            return -1;
        t += 1;
        p = strcspn (t, "!");
        strncpy (ui->sisa, t, p);
        ui->sisa[p] = 0;
        replacestr (ui->sisa, " ", "");

         if ((t = strchr (ui->sisa, 'M'))!=NULL ) // speedyalert bug: ada MB dlm qouta base
            *t  = 0;
#ifdef _DEBUG
        printf ("sisa = %s\n", ui->sisa);
#endif
    }



    strcpy (tmp, ui->quota);
    if ((t = strchr (tmp, 'M'))!=NULL )
    {
        *t = 0;
        quota = strtofloat(tmp);
        inMB  = 1;
#ifdef _DEBUG
        printf ("> strtofloat\n");
#endif
    }
    else if (strchr(tmp,':'))
    {
        quota = strtoseconds(tmp);
#ifdef _DEBUG
        printf ("> strtoseconds\n");
#endif
    }
#ifdef _DEBUG
	printf ("quota = %f (%s)\n", quota, tmp);
#endif

    if (quota>0)
    {
        strcpy (tmp, ui->penggunaan);
        if (inMB)
            penggunaan = strtofloat(tmp);
        else
            penggunaan = strtoseconds(tmp);

#ifdef _DEBUG
        printf ("penggunaan = %f (%s)\n", penggunaan, tmp);
#endif

        ui->penggunaan_persen = 100.0 * penggunaan / quota;
        if (ui->penggunaan_persen)
            sprintf (ui->penggunaan, "%s (%.2f%%)", ui->penggunaan, ui->penggunaan_persen);
    }

    return 1;
}

int geturl (const char *url, const char *nospeedy, char *result)
{
  	char reply[MAXREPLY];
	int get = 0;
	int p = 0;
	char *t;
	char *t2;
	char *t3;
	char func[20];
	char usefunc[20];
	char tmp[256];
	char tmplist[1024*2];

	if ( (get = http_get(url, nospeedy, reply)) != 1 )
        return get;

    t3 = reply;
    memset (tmplist, 0, 1024);
    while (  (t = strstr (t3, "function ")) != NULL )
    {
        t3 = t+20;


        if ( (t2 = strchr (t, ' ')) == NULL )
            continue;
        t2++;

        g_strlcpy (func, t2, 20);

        if ( (t = strchr (func, '(')) == NULL )
            continue;

        *t = 0;

#ifdef _DEBUG
        printf ("> %s\n", func);
#endif

        if ( (t = strstr (t3, "eval(\"")) == NULL)
        {
            break;
        }

        if (*(t-1)=='/')
            continue;

        g_strlcpy (tmp, t, 256);

#ifdef _DEBUG
        printf ("> %s\n", tmp);
#endif
        if ( (t = strstr (tmp, "\");")) == NULL )
            continue;

        *t = 0;

        if ( (t = strstr (tmp, "http")) == NULL )
            continue;

        if ( (t2 = strchr (t, '\'')) == NULL )
            continue;

        *t2 = 0;

        g_strlcpy (tmp, t, 256);
#ifdef _DEBUG
        printf (">> %s\n", tmp);
#endif
        ++p;
        if (p==1)
            strcpy (tmplist, func);
        else
        {
            strcat (tmplist, "|");
            strcat (tmplist, func);
        }
        strcat (tmplist, "|");
        strcat (tmplist, tmp);

#ifdef _DEBUG
        printf ("* %s\n* %d\n", tmplist, strlen(tmplist));
#endif

        t3 += strlen(tmp);
    }

#ifdef _DEBUG
    printf ("* %s\n", tmplist);
#endif

    if (!p)
        return 0;

    if ((t = strstr (t3, "<body "))==NULL)
        return 0;
    if ((t2 = strchr (t, ':'))==NULL)
        return 0;
    t2++;

    g_strlcpy (usefunc, t2, 20);
    if ( (t=strchr(usefunc, '('))==NULL )
        return 0;
    *t = 0;

#ifdef _DEBUG
        printf ("* %s\n", usefunc);
#endif

    strcat (usefunc, "|");
    if ((t=strstr(tmplist, usefunc))==NULL )
        return 0;

    t+=strlen(usefunc);
    g_strlcpy (result, t, 128);
    if ((t=strchr(result, '|'))!=NULL)
        *t = 0;

#ifdef _DEBUG
        printf ("* %s\n", result);
#endif

    return 1;
}
